package org.tds.master;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class InDock extends Activity {
	public final String TAG = "TDS-InDock";
	public Boolean logging = false;
	Button changeState = null;
	Button reset = null;
	public boolean existed = false;
	public long startTime = System.currentTimeMillis();
	final int maxMag = 11;
	SensorManager s;
	TextView output;
	int oldRingType;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "Created");
		super.onCreate(savedInstanceState);
		requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
		setContentView(R.layout.dock_main);
		Log.i(TAG, "should come to front now.");

		output = (TextView) findViewById(R.id.output);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
						| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		// Save old ring volume and set to silent for now
		AudioManager soundManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		oldRingType = soundManager.getRingerMode();
		soundManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
		Log.i(TAG, "Ringer mode changed from " + oldRingType + " to silent");

		registerReceiver(batRC, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

		s = (SensorManager) getApplicationContext().getSystemService(
				Context.SENSOR_SERVICE);
		s.registerListener(sel, s.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);

		takeFocus();
	}

	public void takeFocus() {
		Log.i(TAG, "Taking focus");

		View v = View.inflate(getBaseContext(), R.layout.dock_alert, null);
		AlertDialog.Builder b = new AlertDialog.Builder(getBaseContext());
		b.setCancelable(true);
		b.setTitle("Dock detected!");
		b.setView(v);
		b.setIcon(android.R.drawable.ic_dialog_alert);
		b.setPositiveButton("Abort", l);

		AlertDialog d = b.create();
		d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		d.show();
		d.setButton(DialogInterface.BUTTON_POSITIVE, "Abort", l);
	}

	private DialogInterface.OnClickListener l = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			Toast.makeText(getBaseContext(), "Canceled!", Toast.LENGTH_LONG);
			Log.i(TAG, "Canceled");
			leftDock();
		}
	};

	// This checks to see if it's unplugged which would mean it has left the
	// dock
	public BroadcastReceiver batRC = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			int state = intent.getIntExtra("plugged", -1);
			if (state == 0) {
				leftDock();
			}
		}
	};

	private SensorEventListener sel = new SensorEventListener() {
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// /Log.d(TAG,"Accuracy changed");
		}

		public void onSensorChanged(SensorEvent event) {
			float[] vals = event.values;
			float left = vals[0];
			float down = vals[1];
			float in = vals[2];
			// Log.d(TAG,"Sensor changed- left: "+left+" down: "+down+" in: "+in);
			checkData(left, down, in);
		}
	};

	public float findMag(float... dirs) {
		float rtn = 0;
		for (int i = 0; i < dirs.length; i++) {
			rtn += Math.pow(dirs[i], 2);
		}
		rtn = (float) Math.sqrt(rtn);
		return rtn;
	}

	public void checkData(float l, float d, float i) {
		float mag = findMag(l, d, i);
		output.setText("Magnitude: " + mag);

		if (mag > maxMag) {
			s.unregisterListener(sel);
			Log.i(TAG, "Event detected, going to EventDetected");
			Intent i1 = new Intent(getApplicationContext(), EventDetected.class);
			i1.putExtra("contact1name", getIntent().getExtras().getString(
					"contact1name"));
			i1.putExtra("contact1phone", getIntent().getExtras().getString(
					"contact1phone"));
			i1.putExtra("contact1email", getIntent().getExtras().getString(
					"contact1email"));
			i1.putExtra("contact2name", getIntent().getExtras().getString(
					"contact2name"));
			i1.putExtra("contact2phone", getIntent().getExtras().getString(
					"contact2phone"));
			i1.putExtra("contact2email", getIntent().getExtras().getString(
					"contact2email"));
			i1.putExtra("oldRingType", oldRingType);
			startActivity(i1);

		}
	}

	public void leftDock() {
		Log.i(TAG, "Removed from dock, returning to WaitingForDock");
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		s.unregisterListener(sel);
		Intent i = new Intent(getApplicationContext(), WaitingForDock.class);
		i.putExtra("oldRingType", oldRingType);
		i.putExtra("contact1name", getIntent().getExtras().getString(
				"contact1name"));
		i.putExtra("contact1phone", getIntent().getExtras().getString(
				"contact1phone"));
		i.putExtra("contact1email", getIntent().getExtras().getString(
				"contact1email"));
		i.putExtra("contact2name", getIntent().getExtras().getString(
				"contact2name"));
		i.putExtra("contact2phone", getIntent().getExtras().getString(
				"contact2phone"));
		i.putExtra("contact2email", getIntent().getExtras().getString(
				"contact2email"));
		startActivity(i);
		onDestroy();
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "InDock was destroyed");
		super.onDestroy();
	}

	@Override
	public void onResume() {
		Log.i(TAG, "InDock was resumed");
		super.onResume();
	}

	@Override
	public void onStart() {
		Log.i(TAG, "InDock was started");
		super.onStart();
	}

}
